<template>
  <el-dialog
    :title="`${drawerProps.title}绩效评估`"
    v-model="drawerVisible"
    :draggable="true"
    :overflow="true"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    top="30px"
    width="800px"
    :destroy-on-close="true"
  >
    <el-form
      ref="ruleFormRef"
      style="overflow-y: auto"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      label-width="120px"
      label-position="top"
      :hide-required-asterisk="drawerProps.isView"
    >
      <group-title title="评估人信息"></group-title>
      <el-row>
        <form-item title="所属组织" prop="orgId" :title-span="4" :item-span="8">
          <cascader-select
            v-if="drawerProps.title.indexOf('跨组') !== -1"
            data-key="orgs-evaluate"
            :request-api="
              () =>
                apiService.findTree(
                  'orgs',
                  {
                    $or: [
                      { leader: userUser.userInfo._id },
                      { superVisor: userUser.userInfo._id },
                      { assistantManage: userUser.userInfo._id }
                    ],
                    leaf: '1'
                  },
                  { sort: { sort: 1 }, fields: ['_id', 'name', 'pid'] }
                )
            "
            :config="{ label: 'name', value: '_id' }"
            v-model:item-value="drawerProps.row!.orgId"
            @change="onOrgChage"
          ></cascader-select>
          <cascader-select
            v-else
            data-key="orgs-leader"
            :request-api="
              () =>
                apiService.find(
                  'orgs',
                  { leaf: '1', leader: userUser.userInfo._id },
                  { sort: { sort: 1 }, fields: ['_id', 'name', 'pid'] }
                )
            "
            :config="{ label: 'name', value: '_id' }"
            v-model:item-value="drawerProps.row!.orgId"
            @change="onOrgChage"
          ></cascader-select>
        </form-item>
        <form-item title="评估对象" prop="userId" :title-span="4" :item-span="8">
          <user-select
            ref="userSelectRef"
            @change="onUserChage"
            placeholder="请选择评估对象"
            v-model="drawerProps.row!.userId"
            :param="{ orgId: drawerProps.row!.orgId }"
          ></user-select>
        </form-item>
      </el-row>

      <el-row>
        <form-item title="是否跨组" prop="crossGroup" :title-span="4" :item-span="8">
          <common-select
            data-key="IS_NOT"
            :request-api="() => apiService.findClassify('IS_NOT')"
            v-model="drawerProps.row!.crossGroup"
          ></common-select>
        </form-item>
        <form-item title="评估占比" prop="crossRate" :title-span="4" :item-span="8">
          <common-select
            data-key="crossRate"
            :request-api="() => apiService.findClassify('crossRate')"
            v-model="drawerProps.row!.crossRate"
          ></common-select>
        </form-item>
      </el-row>
      <group-title title="评估信息"></group-title>
      <el-row>
        <form-item title="周期类型" prop="performanceType" :title-span="4" :item-span="8">
          <common-select
            data-key="performanceType"
            placeholder="周期类型"
            :request-api="() => apiService.findClassify('performanceType')"
            :config="{ label: 'name', value: 'value' }"
            v-model="drawerProps.row!.performanceType"
          ></common-select>
        </form-item>
        <form-item title="评估时间" prop="performanceDate" :title-span="4" :item-span="8">
          <el-date-picker
            style="width: 100%"
            type="month"
            v-model="drawerProps.row!.performanceDate"
            placeholder="请选择"
          ></el-date-picker>
        </form-item>
      </el-row>
      <el-row>
        <form-item title="绩效等级" prop="level" :title-span="4" :item-span="8">
          <common-select
            data-key="PERFORMANCE_LEVEL"
            :request-api="() => apiService.findClassify('PERFORMANCE_LEVEL')"
            v-model="drawerProps.row!.level"
          ></common-select>
        </form-item>
        <form-item title="综合评分" prop="avgScore" :title-span="4" :item-span="8">
          <el-input-number
            style="width: 100%"
            :min="0"
            :max="2"
            :step="0.1"
            :precision="1"
            v-model="drawerProps.row!.avgScore"
          ></el-input-number>
        </form-item>
      </el-row>
      <group-title title="评价信息"></group-title>
      <el-row>
        <!-- <WangEditor height="200px" v-model:value="drawerProps.row.summary" :editor-config="editConfig" mode="simple" /> -->
        <form-item v-if="drawerProps.row.level !== 'B'" title="绩效评价" prop="summary" :title-span="4" :item-span="20">
          <el-input
            type="textarea"
            :rows="5"
            v-model="drawerProps.row.summary"
            placeholder="1、绩效评价要真实客观；
2、等级为A、C必填；
3、C等级需要描述待改进关键问题、和同事面谈；"
          ></el-input>
        </form-item>
        <form-item v-else title="绩效评价" :title-span="4" :item-span="20">
          <el-input
            type="textarea"
            :rows="5"
            v-model="drawerProps.row.summary"
            placeholder="1、绩效评价要真实客观；
2、等级为A、C必填；
3、C等级需要描述待改进关键问题、和同事面谈；"
          ></el-input>
        </form-item>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="drawerVisible = false">取消</el-button>
        <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="UserDrawer">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { Performance, Users } from "@/api/types/base";
import { useUserStore } from "@/stores/modules/user";
import apiService from "@/api/services/apiService";
import groupTitle from "@/components/application/form/group-title.vue";
import formItem from "@/components/application/form/form-item.vue";
import commonSelect from "@/components/SelectFilter/common-select.vue";
import userSelect from "@/components/SelectFilter/user-select.vue";
import cascaderSelect from "@/components/SelectFilter/cascader-select.vue";
// import { IEditorConfig } from "@wangeditor/editor";
// import WangEditor from "@/components/WangEditor/index.vue";

const userUser = useUserStore();
const userSelectRef = ref<InstanceType<typeof userSelect> | null>(null);

const rules = reactive({
  userId: [{ required: true, message: "请选择评估对象" }],
  orgId: [{ required: true, message: "请选择所属组织" }],
  crossGroup: [{ required: true, message: "请选择" }],
  crossRate: [{ required: true, message: "请选择" }],
  performanceType: [{ required: true, message: "请选择" }],
  performanceDate: [{ required: true, message: "请选择" }],
  level: [{ required: true, message: "请选择" }],
  avgScore: [{ required: true, message: "请输入" }],
  summary: [{ required: true, message: "请输入" }]
});

interface DrawerProps {
  title: string;
  tbName: string;
  isView: boolean;
  row: Partial<Performance>;
  api?: (tabName: string, params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  tbName: "",
  row: {}
});

const onOrgChage = (value: string) => {
  userSelectRef.value?.refreshParams({ orgId: value });
};

// 接收父组件传过来的环境
const acceptParams = async (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
  if (drawerProps.value.title.indexOf("新增") != -1) {
    let curDate = new Date();
    let [year, month] = [curDate.getFullYear(), curDate.getMonth()];
    let defaultDate = new Date(year, month - 1, 1);
    // 默认上个月
    drawerProps.value.row.performanceDate = defaultDate;
    drawerProps.value.row.orgId = "";
    drawerProps.value.row.state = "0";
    drawerProps.value.row.create_at = new Date();
    drawerProps.value.row.create_user = userUser.userInfo._id;
    drawerProps.value.row.chargeUser = userUser.userInfo._id;
    drawerProps.value.row.chargeUserName = userUser.userInfo.userName;
    drawerProps.value.row.crossGroup = "0";
    drawerProps.value.row.crossRate = "1";
    drawerProps.value.row.avgScore = 1;
    drawerProps.value.row.performanceType = "1";
    drawerProps.value.row.level = "B";
  }
  if (drawerProps.value.title.indexOf("跨组") != -1) {
    drawerProps.value.row.chat_state = "0";
    drawerProps.value.row.crossGroup = "1";
    drawerProps.value.row.crossRate = "0.4";
    drawerProps.value.row.avgScore = 1;
    drawerProps.value.row.orgId = "";
  }
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    if (drawerProps.value.row.userId === drawerProps.value.row.chargeUser) {
      ElMessage.info({ message: "不用给自己评估。" });
      return;
    }
    try {
      if (drawerProps.value.title.indexOf("新增") != -1 && (await checkReapt(drawerProps.value.row))) {
        ElMessage.info({ message: "该用户已存在。" });
      } else {
        await drawerProps.value.api!(drawerProps.value.tbName, drawerProps.value.row);
        ElMessage.success({ message: `${drawerProps.value.title}成功！` });
        drawerProps.value.getTableList!();
        drawerVisible.value = false;
      }
    } catch (error) {
      console.log(error);
    }
  });
};

// 校验用户是否重复
const checkReapt = async row => {
  if (row.performanceDate) {
    let condition: any = {};
    let curDate = new Date(row.performanceDate);
    let [year, month] = [curDate.getFullYear(), curDate.getMonth()];
    let startDate = new Date(year, month, 1);
    let endDate = new Date(year, month + 1, 0, 23, 59, 59);
    condition.performanceDate = { $gte: startDate, $lte: endDate };
    condition.userId = row.userId;
    condition.chargeUser = row.chargeUser;
    let { data } = await apiService.findCount<number>(drawerProps.value.tbName, condition);
    return data > 0;
  }
  return false;
};

const onUserChage = async user => {
  let { data } = await apiService.findOne<Users>("users", { _id: user });
  if (data && data.orgId) {
    drawerProps.value.row.orgId = data.orgId;
  } else {
    ElMessage.info({ message: "该用户未设置所属组织，请联系运维人员。" });
  }
};

defineExpose({
  acceptParams
});
</script>
